package com.example.wordlistdemo.api;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

import java.io.IOException;

public class WordApiRequest {

    private final OkHttpClient client = new OkHttpClient();

    // 替换为实际的API地址
    //private static final String API_URL = "https://www.iciba.com/_next/data/dTlbEbttstfo-ZBl63u0M/word.json?w=";
    private static final String API_URL = "http://dict.youdao.com/jsonapi?xmlVersion=5.1&client=&dicts=&keyfrom=&model=&mid=&imei=&vendor=&screen=&ssid=&network=5g&abtest=&jsonversion=2&q=";

    public void getWordMeaning(String word, final Callback callback) {
        // 构建请求URL
        String requestUrl = API_URL + word;

        // 创建请求
        Request request = new Request.Builder()
                .url(requestUrl)
                .build();

        // 异步执行请求
        client.newCall(request).enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                // 处理请求失败的情况
                callback.onFailure(call, e);
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                // 处理请求成功的情况
                if (response.isSuccessful()) {
                    // 将结果传递给回调
                    callback.onResponse(call, response);
                } else {
                    // 请求失败
                    callback.onFailure(call, new IOException("Unexpected code " + response));
                }
            }
        });
    }
}

